package cc.rengu.redp.bizimpl.csmc.service.impl;

import cc.rengu.redp.bizimpl.csmc.domain.CSubjectInfo;
import cc.rengu.redp.bizimpl.csmc.dao.CSubjectInfoMapper;
import cc.rengu.redp.bizimpl.csmc.service.ICSubjectInfoService;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author lizk
 */
@Service("cSubjectInfoService")
@DS("csmc")
public class CSubjectInfoServiceImpl extends ServiceImpl<CSubjectInfoMapper, CSubjectInfo> implements ICSubjectInfoService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpPrivilegeCheckService UpmpPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;

    private long oprMenuId = 1;
    private String oprMenuName = "清分清算参数管理:科目配置";
    private long chkMenuId = 2;
    private String chkMenuName = "清分清算参数管理:科目配置";
    private String webNextUrl = "/admin/csmc/subjectInfo";


    @Override
    public IPage<CSubjectInfo> findByPage(QueryRequest queryRequest, CSubjectInfo subjectInfo) {

        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        try {
            String instId = subjectInfo.getInstId();
            if (Common.isBlank(instId)) {
                instId = user.getInstId();
            }
            LambdaQueryWrapper<CSubjectInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(instId)) {
                queryWrapper.eq(CSubjectInfo::getInstId, instId);
            }
            if (!StringUtils.isEmpty(subjectInfo.getSettleAcctDesc())) {
                queryWrapper.like(CSubjectInfo::getSettleAcctDesc, subjectInfo.getSettleAcctDesc());
            }
            queryWrapper.orderByDesc(CSubjectInfo::getCreateTime);
            Page<CSubjectInfo> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("获取科目配置信息失败", e);
            return null;
        }
    }

    @Override
    public void createSubjectInfo(CSubjectInfo subjectInfo) throws RedpException {
        saveData(subjectInfo);
    }

    @Override
    public void updateSubjectInfo(CSubjectInfo subjectInfo) throws RedpException {
        saveData(subjectInfo);
    }

    @Override
    public Map<String, Object> tagsData(String q, String flag, QueryRequest request) {

        if (null == q) {
            return null;
        }

        try {
            LambdaQueryWrapper<CSubjectInfo> queryWrapper = new LambdaQueryWrapper<>();
            if ("select2".equals(flag)){
                queryWrapper.eq(CSubjectInfo::getOprStatus, "01");
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(q)) {
                queryWrapper.and(qw -> qw.likeRight(CSubjectInfo::getSettleAcctId, q)
                        .or().likeRight(CSubjectInfo::getSettleAcctDesc, q));
            }

            Page<CSubjectInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<CSubjectInfo> page1 = this.page(page, queryWrapper);
            List<CSubjectInfo> listx = page1.getRecords();
            Map<String, Object> maps = new HashMap<String, Object>();
            Map<String, String> map = new HashMap<String, String>();
            List<Object> list = new ArrayList<Object>();
            if (listx != null) {
                for (int i = 0; i < listx.size(); i++) {
                    CSubjectInfo org = listx.get(i);
                    map = new HashMap<String, String>();
                    map.put("id", org.getSettleAcctId());
                    map.put("name", org.getSettleAcctDesc());

                    list.add(map);
                }
                maps.put("results", list);
                maps.put("total", page.getTotal());
                int pageIndex = Common.isBlank(request.getPageNum()) ? 1 : request.getPageNum();
                if (pageIndex == page1.getTotal()) {
                    maps.put("more", false);
                } else {
                    maps.put("more", true);
                }
            }
            return maps;

        } catch (Exception e) {
            log.error("获取信息失败", e);
            return null;
        }
    }

    private void saveData(CSubjectInfo entity) throws RedpException {

        String optFlag = entity.getOptFlag();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

//        entity.setInstId(user.getInstId());

        if (isRepeat(entity.getInstId(), entity.getSettleAcctId(), entity.getId())) {
            throw new RedpException("科目/账号标识已存在");
        }
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            UpmpPrivilegeCheck privilegeCheck = UpmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "subjectInfo:add");
            entity.setId(null);
            entity.setOprId(user.getId());
            entity.setCreateTime(lastUpddt);
            //
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                entity.setOprStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                this.save(entity);
                bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        entity.getOprStatus(), entity.getAuditStatus(), entity.getId(), webNextUrl, null, null, null);

            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                entity.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                this.save(entity);
                bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        entity.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) {

            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            UpmpPrivilegeCheck privilegeCheck = UpmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "subjectInfo:edit");

            CSubjectInfo dbsubjectinfo = baseMapper.selectById(id);
            CSubjectInfo subjectinfo = new CSubjectInfo();
            CSubjectInfo subjectinfoTmp = new CSubjectInfo();
            BeanUtils.copyProperties(dbsubjectinfo, subjectinfo);
            BeanUtils.copyProperties(dbsubjectinfo, subjectinfoTmp);

            entity.setAuditOprId(user.getId());
            entity.setUpdateTime(lastUpddt);
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                baseMapper.updateById(subjectinfo);

                //检查临时表是否有数据，如果没用则新增
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                BeanUtils.copyProperties(entity, subjectinfoTmp);

                bizTmpService.saveBizTmp(subjectinfoTmp, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        subjectinfoTmp.getOprStatus(), subjectinfoTmp.getAuditStatus(), subjectinfoTmp.getId(), webNextUrl, null, null, null);

            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());

                BeanUtils.copyProperties(entity, subjectinfo);
                baseMapper.updateById(subjectinfo);

                //历史表新增
                bizHisService.saveBizHisNew(subjectinfo, dbsubjectinfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        subjectinfo.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {
            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            CSubjectInfo subjectinfodb = baseMapper.selectById(id);
            CSubjectInfo subjectinfo = new CSubjectInfo();
            BeanUtils.copyProperties(subjectinfodb, subjectinfo);
            if (Common.isBlank(subjectinfo)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";

            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = UpmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "subjectInfo:stop");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                    subjectinfo.setOprStatus(subjectinfo.getOprStatus());
                } else {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    subjectinfo.setOprStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)) {

                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = UpmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "subjectInfo:use");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                    subjectinfo.setOprStatus(subjectinfo.getOprStatus());
                } else {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    subjectinfo.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {

                String cancelReason = entity.getCancelReason();
                subjectinfo.setCancelReason(cancelReason);
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = UpmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "subjectInfo:cancel");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                    subjectinfo.setOprStatus(subjectinfo.getOprStatus());
                } else {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    subjectinfo.setOprStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                }
            }
            subjectinfo.setAuditOprId(user.getId());
            subjectinfo.setUpdateTime(lastUpddt);
            baseMapper.updateById(subjectinfo);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmp(subjectinfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        subjectinfo.getOprStatus(), subjectinfo.getAuditStatus(), subjectinfo.getId(), webNextUrl, null, null, null);

            } else {
                //历史表新增
                bizHisService.saveBizHisNew(subjectinfo, subjectinfodb, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        subjectinfo.getId(), null, null, null);

            }

        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {

            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }

            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getBizTmpDetail(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据！");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            CSubjectInfo subjectinfoNew = JSON.parseObject(bizdata, CSubjectInfo.class);

            CSubjectInfo subjectinfo = baseMapper.selectById(id);
            CSubjectInfo subjectinfold = new CSubjectInfo();
            BeanUtils.copyProperties(subjectinfo, subjectinfold);
            if (Common.isBlank(subjectinfo) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }

            String opt = entity.getOpt();
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                throw new RedpException("请求参数(opt)异常!");
            }
//
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                // 审批通过将临时表数据更新到正式表
                BeanUtils.copyProperties(subjectinfoNew, subjectinfo);
            } else {
                String approvalRefuseReason = entity.getAuditRefuseReason();
                subjectinfo.setAuditRefuseReason(approvalRefuseReason);
            }
            String bizOpr = "";
            String approvalRefuseReason = entity.getAuditRefuseReason();
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(subjectinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    subjectinfo.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(subjectinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    subjectinfo.setOprStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                } else {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(subjectinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    subjectinfo.setOprStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                } else {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_STOP.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(subjectinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    subjectinfo.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_USE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(subjectinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                    subjectinfo.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    subjectinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }

            baseMapper.updateById(subjectinfo);
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(subjectinfo, subjectinfold, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), chkMenuName,
                        subjectinfo.getId(), null, null, null);

            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(subjectinfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                    String.valueOf(chkMenuId), chkMenuName,
                    subjectinfo.getOprStatus(), subjectinfo.getAuditStatus(), subjectinfo.getId(), webNextUrl, null, null, null);
        }

    }

    /**
     * 判断是否重复
     */
    public boolean isRepeat(String instId, String settleAcctId, String id) {
        LambdaQueryWrapper<CSubjectInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CSubjectInfo::getInstId, instId).eq(CSubjectInfo::getSettleAcctId, settleAcctId);

        CSubjectInfo subjectInfo = baseMapper.selectOne(wrapper);
        if (Common.isBlank(id)) {
            if (Common.isNotBlank(subjectInfo)) {
                return true;
            }
        } else {
            if (Common.isNotBlank(subjectInfo) && !id.equals(subjectInfo.getId())) {
                return true;
            }
        }
        return false;
    }

}
